<template>
  <div>
    <el-dropdown>
      <SvgIcon name="en-or-ch" size="20" />
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item v-for="item in languages" :key="item.value" :disabled="language===item.value">
            <span @click="handleSetLanguage(item.value)">{{ item.name }}</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import SvgIcon from '@/components/SvgIcon/index.vue'
import { computed, ref } from 'vue';
import store from "@/store";
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router'

type Language = {
  name: string
  value: string
}
const $router = useRouter()
const languages = ref<Language[]>([
  { name: 'English', value: 'en' },
  { name: '中文', value: 'zh-cn' }
])
const { locale } = useI18n()
// 切换语言
const handleSetLanguage = async (lang: string) => {
  if (locale.value === lang) return
  locale.value = lang
  await store.dispatch('app/setLanguage', lang)
  $router.go(0)
  ElMessage({
    message: '切换语言成功',
    type: 'success'
  })
}
const language = computed(() => {
  return store.state.app.language
})
</script>